package com.stm.bi.report;

import com.alibaba.fastjson.JSONObject;
import com.stm.base.api.RegionRemoteService;
import com.stm.base.dto.vo.RegionDetailVO;
import com.stm.base.provider.DictionaryProvider;
import com.stm.bi.core.util.DateUtils;
import com.stm.bi.dto.query.RegionalSaleQuery;
import com.stm.bi.dto.vo.RegionalStyleSalesVO;
import com.stm.file.api.AttachmentRemoteService;
import com.stm.file.dto.vo.AttachmentVO;
import com.stm.framework.core.context.UserHolder;
import com.stm.framework.dbcp.JdbcService;
import com.stm.framework.dto.Response;
import com.stm.saas.api.CalendarCycleRemoteService;
import com.stm.saas.api.ProductConfigRemoteService;
import com.stm.saas.api.ProductStyleRemoteService;
import com.stm.saas.dto.query.ProductStylePageQry;
import com.stm.saas.dto.vo.ProductConfigVO;
import com.stm.saas.dto.vo.ProductStyleQueryVO;
import com.stm.saas.model.CalendarCycle;
import com.stm.bi.model.DateRange;
import com.stm.bi.dto.vo.ProductStyleDataVO;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

import static com.stm.bi.constant.PlanConstants.TYPE_MONTH;
import static com.stm.bi.constant.PlanConstants.TYPE_YEAR;
import static com.stm.saas.constant.DimensionConstants.PRODUCT_STYLE_DIMENSION_ID;
import static com.stm.saas.constant.IndexConstants.*;
import static com.stm.saas.constant.IndexConstants.BUSINESS_ID_FIELD_NAME;

/**
 * @author liuyx
 * @date 2025/2/14 9:09
 */
@Component
public class RegionalStyleSalesQueryExe extends AbsChartQueryExe<RegionalSaleQuery, RegionalStyleSalesVO> {
    @Resource
    private JdbcService jdbcService;

    @Resource
    private CalendarCycleRemoteService calendarCycleRemoteService;

    @Resource
    private DictionaryProvider dictionaryProvider;

    @Resource
    private ProductStyleRemoteService productStyleRemoteService;
    @Resource
    private RegionRemoteService regionRemoteService;
    @Resource
    private AttachmentRemoteService attachmentRemoteService;
    @Resource
    private ProductConfigRemoteService productConfigRemoteService;

    private final String IMAGE_SIZE = "image/quality,q_60";

    @Override
    public RegionalStyleSalesVO query(Long orgId, String orgNo, RegionalSaleQuery regionalSaleQry) {
        RegionalStyleSalesVO vo = new RegionalStyleSalesVO();
        vo.setRegionName("全国");
        // 查全部
        CalendarCycle cyc = calendarCycleRemoteService.getByOrg().get();
        DateRange dateRange = DateUtils.getYearFirstAndEnd(LocalDate.now().toString(), cyc.getMonth());
        String allSql = "select * from ads_base_province_sales where org_id = ? and dept_id = ? and date_type = ? and date between ? and ?  ";
        Response<ProductConfigVO> resp = productConfigRemoteService.selectByOrgId(UserHolder.getOrgId());
        // 拼接水准
        String salesDefinition = "dealing";
        if(resp != null && resp.getData() != null) {
            salesDefinition = resp.getData().getSalesDefinition();
        }
        if("delivery".equals(salesDefinition)) {
            salesDefinition = "dealing";
        }
        allSql = allSql + " and sales_type = '" + salesDefinition + "'";
        List<Map> maps = jdbcService.selectList(allSql, new Object[]{
                orgId,
                regionalSaleQry.getDeptId(),
                TYPE_MONTH,
                dateRange.getStartDate(),
                dateRange.getEndDate()});

        String year = String.valueOf(LocalDate.now().getYear());
        if (maps.isEmpty()) {
            return vo;
        }
        maps.sort(Comparator.comparing((Map m) -> ((BigDecimal) m.get(QTY_FIELD_NAME))).reversed());
        //总销量
        double totalQty = maps.stream().map(m -> (BigDecimal) m.get(QTY_FIELD_NAME)).filter(Objects::nonNull).mapToDouble(BigDecimal::doubleValue).sum();

        List<ProductStyleDataVO> productStyleData = new ArrayList<>();
        List<Map> res = new ArrayList<>();
        if (regionalSaleQry.getRegionCode() == null || regionalSaleQry.getRegionCode().isEmpty()) {
            // 全国
            vo.setRegionName("全国")
                    .setSalesVolume(BigDecimal.valueOf(totalQty))
                    .setProportion(BigDecimal.valueOf(100))
                    .setSalesGrade("1");
            // 款式详情
            String nationSql = "select * from ads_base_product_multi_sales where org_id = ? and dept_id = ? and date_type = ? and date = ? ";
            nationSql = nationSql + " and sales_type = '" + salesDefinition + "'";
            List<Map> nationMaps = jdbcService.selectList(nationSql, new Object[]{
                    orgId,
                    regionalSaleQry.getDeptId(),
                    TYPE_YEAR,
                    year});
            // 根据款式编码分组 （商品款式空指针）
            nationMaps = nationMaps.stream()
                    .filter(map -> map.get("style_code") != null)
                    .collect(Collectors.groupingBy(
                            map -> map.get("style_code"),
                            Collectors.collectingAndThen(
                                    Collectors.toList(),
                                    list -> {
                                        BigDecimal qty = list.stream()
                                                .map(map -> (BigDecimal) map.get("qty"))
                                                .reduce(BigDecimal.ZERO, BigDecimal::add);

                                        Map<String, Object> resultMap = new HashMap<>();
                                        resultMap.put("style_code", list.get(0).get("style_code"));
                                        resultMap.put("style_name", list.get(0).get("style_name"));
                                        resultMap.put("qty", qty);
                                        return resultMap;
                                    }
                            )
                    ))
                    .values().stream()
                    .collect(Collectors.toList());
            nationMaps.sort(Comparator.comparing((Map m) -> ((BigDecimal) m.get(QTY_FIELD_NAME))).reversed());
            res = nationMaps.subList(0, Math.min(5, nationMaps.size()));
        } else {
            Response<RegionDetailVO> regionDetailVOResponse = regionRemoteService.selectById(Long.valueOf(regionalSaleQry.getRegionCode()));
            if (regionDetailVOResponse.isSuccess() && regionDetailVOResponse.getData() != null) {
                vo.setRegionName(regionDetailVOResponse.getData().getName());
            }
            // 款式省份
            String nationSql = "select * from ads_base_product_style_province_sales where org_id = ? and dept_id = ? and date_type = ? and date = ? and province_code = ? ";
            nationSql = nationSql + " and sales_type = '" + salesDefinition + "'";
            List<Map> provinceMaps = jdbcService.selectList(nationSql, new Object[]{
                    orgId,
                    regionalSaleQry.getDeptId(),
                    TYPE_YEAR,
                    year,
                    regionalSaleQry.getRegionCode()});
            // 总销量
            double provinceQty = provinceMaps.stream().filter(e -> e.get("province_code").equals(regionalSaleQry.getRegionCode())).map(m -> (BigDecimal) m.get(QTY_FIELD_NAME)).filter(Objects::nonNull).mapToDouble(BigDecimal::doubleValue).sum();
            provinceMaps.sort(Comparator.comparing((Map m) -> ((BigDecimal) m.get(QTY_FIELD_NAME))).reversed());
            res = provinceMaps.subList(0, Math.min(5, provinceMaps.size()));
            // 设置选中省份内容
            // 排名
            Map<String, BigDecimal> provinceTotalQtyMap = maps.stream()
                    .collect(Collectors.groupingBy(
                            m -> (String) m.get("province_code"),
                            Collectors.reducing(
                                    BigDecimal.ZERO,
                                    m -> (BigDecimal) m.get(QTY_FIELD_NAME),
                                    BigDecimal::add
                            )
                    ));
            // 按销量倒序排序
            provinceTotalQtyMap = provinceTotalQtyMap.entrySet().stream()
                    .sorted(Map.Entry.<String, BigDecimal>comparingByValue().reversed())
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            Map.Entry::getValue,
                            (oldValue, newValue) -> oldValue,
                            LinkedHashMap::new
                    ));
            Map<String, BigDecimal> finalProvinceTotalQtyMap = provinceTotalQtyMap;
            // 计算排名
            int grade = IntStream.range(0, finalProvinceTotalQtyMap.size())
                    .filter(i -> finalProvinceTotalQtyMap.keySet().toArray(new String[0])[i].equals(regionalSaleQry.getRegionCode()))
                    .findFirst()
                    .orElse(-1);
            vo.setRegionCode(regionalSaleQry.getRegionCode())
                    .setSalesVolume(BigDecimal.valueOf(provinceQty))
                    .setProportion(BigDecimal.valueOf(100 * provinceQty / totalQty).setScale(2, RoundingMode.HALF_UP));
            if (grade >= 0) {
                vo.setSalesGrade(grade + 1 + "");
            }
        }
        // 查询款式内容和缩略图
        ProductStylePageQry productStylePageQry = new ProductStylePageQry();
        List<String> codes = res.stream().map(e -> (String) e.get("style_code")).collect(Collectors.toList());
        List<ProductStyleQueryVO> prods = new ArrayList<>();
        Map<String, List<AttachmentVO>> imageMap = new HashMap<>();
        if (ObjectUtils.isNotEmpty(codes)) {
            productStylePageQry.setCodes(codes);
            Response<List<ProductStyleQueryVO>> prodResp = productStyleRemoteService.selectList(productStylePageQry);
            if (prodResp.isSuccess() && prodResp.getData() != null) {
                prods = prodResp.getData();

                List<String> imageIds = prods.stream()
                        .map(ProductStyleQueryVO::getImageBusinessId)
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                if (!imageIds.isEmpty()) {
                    Response<Map<String, List<AttachmentVO>>> imageResp = attachmentRemoteService.selectMapByBusinessIds(imageIds, IMAGE_SIZE);

                    if (!imageResp.isSuccess()) {
                        return vo;
                    }
                    imageMap = imageResp.getData();
                } else {
                    imageMap = new HashMap<>();
                }
            }
        }
        for (Map re : res) {
            BigDecimal qty = (BigDecimal) re.get(QTY_FIELD_NAME);
            if (qty.compareTo(BigDecimal.ZERO) == 0) {
                continue;
            }
            ProductStyleDataVO productStyleDataVO = new ProductStyleDataVO();
            productStyleDataVO.setName((String) re.get("style_name"));
            productStyleDataVO.setQty(qty);
            if (!prods.isEmpty() && !imageMap.isEmpty()) {
                Map<String, List<AttachmentVO>> finalImageMap = imageMap;
                prods.stream().filter(e -> e.getCode().equals(re.get("style_code"))).findFirst().ifPresent(e ->{
                    if (finalImageMap.get(e.getImageBusinessId()) != null){
                        productStyleDataVO.setImageUrl(finalImageMap.get(e.getImageBusinessId()).get(0).getFullPath());
                    }
                });
            }
            productStyleData.add(productStyleDataVO);
        }
        // 确保 productStyleData 中有 5 个对象，不足的部分补充空对象
        int requiredLength = 5;
        if (!productStyleData.isEmpty()) {
            while (productStyleData.size() < requiredLength) {
                productStyleData.add(new ProductStyleDataVO());
            }
        }
        vo.setProductStyleData(productStyleData);
        return vo;
    }

    @Override
    public String getReportName() {
        return "区域款式销量";
    }
}
